import { ref, computed, onMounted, onUnmounted } from 'vue';
import { createHvacService, type IHvacService } from '../services/ApiAdapter';
import { MAX_SERVICE_OBJECTS, WAIT_TIME } from '../constants/index';
import { API_MODE } from '../config';

export function useHvacService() {
  // 创建服务实例
  const hvacService = createHvacService(MAX_SERVICE_OBJECTS, WAIT_TIME);
  
  // 强制刷新标记
  const refreshKey = ref(0);
  
  // 更新间隔定时器（仅本地模式）
  let updateInterval: ReturnType<typeof setInterval> | null = null;

  // 初始化
  onMounted(() => {
    // 注册状态变化回调
    if (hvacService.onStateChange) {
      hvacService.onStateChange(() => {
        refreshKey.value++;
      });
    }

    // 启动定时更新（仅本地模式）
    if (hvacService.updateServiceMetrics) {
      updateInterval = setInterval(() => {
        hvacService.updateServiceMetrics!();
        refreshKey.value++;
      }, 1000);
    }
  });

  // 清理
  onUnmounted(() => {
    if (updateInterval) {
      clearInterval(updateInterval);
    }
    hvacService.destroy();
  });

  // 计算属性
  const allRooms = computed(() => {
    refreshKey.value; // 依赖刷新标记
    return hvacService.getAllRoomStates();
  });

  const serviceQueue = computed(() => {
    refreshKey.value;
    return hvacService.getServiceQueue();
  });

  const waitingQueue = computed(() => {
    refreshKey.value;
    return hvacService.getWaitingQueue();
  });

  const allBills = computed(() => {
    refreshKey.value;
    return hvacService.billingService?.getAllBills() || [];
  });

  const occupiedRooms = computed(() => {
    refreshKey.value;
    return hvacService.getOccupiedRooms();
  });

  const checkInRecords = computed(() => {
    refreshKey.value;
    return hvacService.getOccupiedRooms().map(roomId => 
      hvacService.getCheckInRecord(roomId)!
    ).filter(record => record !== null);
  });

  return {
    hvacService,
    refreshKey,
    allRooms,
    serviceQueue,
    waitingQueue,
    allBills,
    occupiedRooms,
    checkInRecords
  };
}

